﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebCurriculumn.Helper;
using System.Configuration;
using WebCurriculumn.Helps;
using WebCurriculumn.DBAcess;
using System.Data;

namespace WebCurriculumn
{
    public partial class Logon : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                Session.Abandon();
                Session["hasLogon"] = "0";
            }
            lblErr.Text = "";
            string sgpid = Request.QueryString["sgpid"];
            if (string.IsNullOrEmpty(sgpid))
            {
                sgpid = Request.Form["iSubjectGradeProfileID"];
            }
            else
            {
                sgpid = Decrypt(sgpid);
            }
            if (string.IsNullOrEmpty(sgpid))
                sgpid = "-1";
            iSubjectGradeProfileID.Text = sgpid;
            Session["iSubjectGradeProfileID"] = sgpid;

            //string iGaki = Request.QueryString["gno"];
            //if (string.IsNullOrEmpty(iGaki))
            //{
            //    iGaki = Request.Form["iGaki"];


            //}
            //if (string.IsNullOrEmpty(iGaki))
            //    iGaki = "-1";
            //txtGaki.Text = iGaki;

            //Session["iGaki"] = iGaki;
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            //txtDomainName.Text = "";
            txtUserName.Text = "";
            txtPassword.Text = "";
            txtUserName.Focus();
        }

        private string Decrypt(string value)
        {
            string returnValue = "";
            for (int i = 0; i < value.Length; i++)
            {
                returnValue += ((char)((int)value[i] - 17)).ToString();
            }
            return returnValue.Substring(0, returnValue.Length - 2); ;
        }
        private bool checkInput()
        {
            if (txtUserName.Text == "")
            {
                lblErr.Text = "ユーザー名を入力してください。";
                txtUserName.Focus();
                return false;
            }
            if (txtPassword.Text == "")
            {
                lblErr.Text = "パスワードを入力してください。";
                txtPassword.Focus();
                return false;
            }
            return true;
        }
        private bool CheckPublicDate()
        {
            if (Session["iSubjectGradeProfileID"] != null)
            {
                int sgpid = MyUtils.ParseToInt(Session["iSubjectGradeProfileID"], 0);
                using (DBContext db = new DBContext())
                {
                    SqlResult result = db.CallProcedure("usp_tbsTRPublic_getBySGPid", sgpid);
                    if (result.DataSet.Tables.Count > 0 && result.DataSet.Tables[0].Rows.Count > 0)
                    {
                        DataTable dt = result.DataSet.Tables[0];
                        DateTime dtStart = MyUtils.ParseToDateTime(dt.Rows[0]["dtPublicS"], DateTime.Now);
                        DateTime dtEnd = MyUtils.ParseToDateTime(dt.Rows[0]["dtPublicE"], DateTime.Now);
                        if (dtStart.CompareTo(DateTime.Now) < 0 && dtEnd.CompareTo(DateTime.Now) > 0)
                        {
                            return true;
                        }
                        else
                        {
                            lblErr.Text = "公開時間以内がないです";
                            return false;
                        }
                    }
                    else
                    {
                        lblErr.Text = "公開時間以内がないです";
                        return false;
                    }

                }
            }
            return false;
        }
        protected void btnLogon_Click(object sender, System.EventArgs e)
        {
            if (checkInput() == false|| CheckPublicDate()==false)
            {
                return;
            }
            //Novell LDAP,S------        
            try
            {
                Session["hasLogon"] = "0";
                bool isAuthen = false;
                //test,s
                if (ConfigurationManager.AppSettings["HasLDAP"] == "1")
                {
                    LdapAuthentication adAuth = new LdapAuthentication();

                    isAuthen = adAuth.IsAuthenticated(txtUserName.Text, txtPassword.Text);
                }
                else
                    isAuthen = true;

                if (isAuthen)
                //test,E
                {
                    Session["hasLogon"] = "1";
                    Session["LogonID"] = txtUserName.Text;
                    //FormsAuthenticationTicket authTicket1 =
                    //           new FormsAuthenticationTicket(1,  // version
                    //                                         txtUserName.Text,
                    //                                         DateTime.Now,
                    //                                         DateTime.Now.AddMinutes(60),
                    //                                         false, "Group1|Group2|Group3|");
                    //// Now encrypt the ticket.
                    //string encryptedTicket1 = FormsAuthentication.Encrypt(authTicket1);

                    //HttpCookie authCookie1 =
                    //                new HttpCookie(FormsAuthentication.FormsCookieName,
                    //                               encryptedTicket1);
                    //// Add the cookie to the outgoing cookies collection. 
                    //Response.Cookies.Add(authCookie1);

                    //Response.Redirect(
                    //                  FormsAuthentication.GetRedirectUrl(txtUserName.Text, false));

                    //Response.Redirect("StudentScoreList.aspx");
                    //string iGaki = txtGaki.Text;
                    //if (iGaki == "1")
                    //    Server.Transfer("StudentScoreList.aspx");
                    //else if (iGaki == "2")
                    //    Server.Transfer("StudentScoreList2.aspx");

                    //else if (iGaki == "99")
                    //    Server.Transfer("StudentScoreList99.aspx");
                    //else

                    //    lblErr.Text = "アクセスエラー";
                    //return;
                    LogHelper.WriteLog("LDAP認証", "認証成功", txtUserName.Text);
                    Response.Redirect("CurriCulumnEdit.aspx?subjectgradeId=" + Session["iSubjectGradeProfileID"].ToString());


                }
                else
                {
                    lblErr.Text = "認証失敗";
                    LogHelper.WriteLog("LDAP認証", "認証失敗", txtUserName.Text);
                    return;
                }
            }

            //Novell LDAP,E--------


            catch (Exception ex)
            {
                lblErr.Text = ex.Message;
            }
        }
    }
}
